package com.springboot2.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot2.entity.Files;
import com.springboot2.mapper.FilesMapper;
import com.springboot2.service.FilesService;
import com.springboot2.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 文件上传
 * */
@RestController
@RequestMapping("/file/")
class FilesController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private FilesService filesService;

    //增
    @PostMapping("save")
    public Result save (@RequestBody Files files){
        filesService.add(files);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del (@PathVariable int id){
        filesService.del(id);
        return  Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody Files files){
        filesService.update(files);
        return Result.success();
    }
    //获取对象
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(filesService.findById(id));
    }
    //分页列表
    @GetMapping("listPage/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo, @PathVariable int pageSize){
        Map<String,Object> map = new HashMap<>();
        map.put("data",filesService.findByPage(pageNo, pageSize));
        map.put("total",filesService.count());

        return Result.success(map);
    }
    //列表
    @GetMapping("list")
    public Result findAll(){
        return Result.success(filesService.findAll());
    }
    //查询条件
    //批量删除
    @DeleteMapping("batch/{ids}")
    @Transactional
    public Result delAll(@PathVariable String ids){
        String[] split = ids.split(",");
        for (String id:split){
            filesService.del(Integer.parseInt(id));
        }
        return  Result.success();
    }

    /*
     * 文件上传
     * */

    @PostMapping("/upload")
    public  String upload(@RequestParam MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        //定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID= uuid+ StrUtil.DOT+type;
        File uploadFile = new File(fileUploadPath + fileUUID);

        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdir();
        }
        //获取文件md5
        String url;
        String md5;
        //当文件存在的时候再获取文件的md5
        file.transferTo(uploadFile);

        md5 = SecureUtil.md5(uploadFile);
//        Files dbFiles = getFileByMd5(md5);
//        if(dbFiles != null){
//            url= dbFiles.getUrl();
//            uploadFile.delete();
//        }else {
//            //把获取到的文件存储到磁盘目录上去
//           // file.transferTo(uploadFile);
//            url= "http://localhost:8000/file/"+fileUUID;
//        }
        url= "http://localhost:8000/file/"+fileUUID;
        //再存储到数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        filesService.add(saveFile);
        return url;
    }

    /*
     * 文件下载
     * */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath +fileUUID);
        // 设置输出的格式
        ServletOutputStream os = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");
        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
    /*
     * 通过文件的md5查询文件
     * @params md5
     * return Files
     * */
    private Files getFileByMd5(String md5){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5",md5);
        List<Files> filesList = filesService.findAll();
        return filesList.size() ==0?null:filesList.get(0);
    }

}
